package com.lagou.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: wudong
 * @create: 2021-05-19 14:02
 **/
public class DefaultConectionManager implements ConectionManager {
    private DataSource dataSource;
    private Connection connection;
    private boolean autoCommit;

    public DefaultConectionManager(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }

    @Override
    public Connection getConnection() throws SQLException {
        if(connection == null){
            connection = dataSource.getConnection();
            if(connection.getAutoCommit() != autoCommit){
                connection.setAutoCommit(autoCommit);
            }
        }
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if(connection != null && !connection.getAutoCommit()){
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if(connection != null && !connection.getAutoCommit()){
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if(connection != null){
            connection.setAutoCommit(true);
            connection.close();
        }
    }
}
